import { message, Card, Form, Button, Input } from 'antd';
import userModel from '../../model/userModel';
import { UserInfoType } from '../register/Register';
import { useDispatch } from "react-redux";
import './index.css'
import { initUser } from '../../action/userAction';

export default (props: any) => {

  const dispatch = useDispatch();

  const onFinish = async (info: UserInfoType) => {
    
    //检查用户名和密码是否匹配
    const { data: list } = await userModel.query({
      ...info
    });
    
    if (list.length) {
      //判断长度
      const userinfo = list[0];
      window.localStorage.setItem("userinfo", JSON.stringify(userinfo));
      dispatch(initUser(userinfo));
      message.success('登录成功')
      props.history.push("/live");
    } else {
      message.error('用户名和密码不匹配');
    }
  };

  const onFinishFailed = () => {
    message.error('请检查红色的错误提示');
  };

  const goToRegister = () => {
    props.history.push("/register");
  }


  return (
    <div className='warp'>
      <Card className='card' title='登录'>
        <Form
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="on"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入2到10位英文字母和数字及下划线' },
            { pattern: /[\u4e00-\u9fa5_a-zA-Z0-9_]{2,10}/, message: '请输入2到10位英文字母和数字及下划线' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入数字字母_$组成长度6到10位' },
            { pattern: /^[a-z_$0-9]{3,10}$/i, message: '请输入数字字母_$组成长度6到10位' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
        <Button type='link' onClick={goToRegister}>去注册</Button>
      </Card>
    </div>
  );
};

